import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
// import type {RespDto} from '../interface/dto/common'
import router from '../router/index.ts'

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: "/api", // 请求地址
  timeout: 30000 // 超时时间
})

service.interceptors.request.use(
  config => {
    //获取token
    const token:string | null = localStorage.getItem(import.meta.env.VITE_TOKEN_VALUE);
    if(token){
      config.headers.Authorization = token
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


service.interceptors.response.use(
  response => {
    // 关闭loading
    if(response.data.code === 1200){
      return Promise.resolve(response.data.data)
    }else {
      let msg = response.data.msg
      //自定义失败，允许的常见失败
      if(response.data.code === 1411){
      }
      //参数错误
      else if(response.data.code === 1400){
      }
      //未授权
      else if(response.data.code === 1401){
        localStorage.removeItem(import.meta.env.VITE_TOKEN_VALUE);
        router.push({name:"login"})
      }
      //权限不足
      else if(response.data.code === 1403){
      }
      //资源不存在
      else if(response.data.code === 1404){
      }
      //客户端多次请求
      else if(response.data.code === 1429){
      }
      //系统未知异常，不允许的常见失败
      else if(response.data.code === 1511){
      }
      //未定义的异常
      else{
        msg = "未知错误"
      }

      ElMessage({
        message: msg,
        grouping: true,
        type: 'warning'
      });
      return Promise.reject(response.data);
    }
  },
  error => {
    // 处理异常情况，根据项目实际情况处理或不处理
    if (error && error.response) {
      // 根据约定的响应码处理
      switch (error.response.status) {
        case 403:
          error.message = '拒绝访问';
          break;
        case 502:
          error.message = '服务器端出错';
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    } else {
      // 超时处理
      error.message = '服务器响应超时，请刷新当前页';
    }
    ElMessage({
      message: "请求异常:"+error.message,
      grouping: true,
      type: 'error'}
    );
    return Promise.reject(error.response);
  }
);


//get请求
export function get<T>(path:string,param?:object):Promise<T>{
  const requestParam:AxiosRequestConfig = {};
  requestParam.params = param
  return service.get(path,requestParam);
}


//post json请求
export function postJson<T>(path:string,param:object):Promise<T>{
  return service.post(path,param);
}

//post 表单请求
export function postForm<T>(path:string,param:object):Promise<T>{
  return service.postForm(path,param);
}

//put json请求
export function putJson<T>(path:string,param:object):Promise<T>{
  return service.put(path,param);
}


//put 表单请求
export function putForm<T>(path:string,param:object):Promise<T>{
  return service.putForm(path,param);
}


//delete json请求
export function deleteJson<T>(path:string,param:object):Promise<T>{
  return service.delete(path,param);
}

export default service